package test;

import java.util.Arrays;

/**
 * 
 * @author  
 * @date    2010-10-29
 * @file    test.FindTopValuesImpl.java
 */
public class FindTopValuesImpl implements FindTopValues{
	/**
	 * 计算最大值不需排序，直接扫描一遍即可
	 */
	@Override
	public int findMaxValue(int[] anyOldOrderValues) {
		if (anyOldOrderValues == null){
			throw new RuntimeException("The anyOldOrderValues cann't be null.");
		}
		if (anyOldOrderValues.length == 1){
			return anyOldOrderValues[0];
		}
		int max = anyOldOrderValues[0];
		for (int i=1; i<anyOldOrderValues.length; ++i){
			if (max < anyOldOrderValues[i]){
				max = anyOldOrderValues[i];
			}
		}
		return max;
	}
	/**
	 * 计算前 N 个最大值可采用快速排序Arrays.sort(int[] a)， 性能 JDK 中描述为：
	 * This algorithm offers n*log(n) performance on many data sets
	 */
	@Override
	public int[] findTopNValues(int[] anyOldOrderValues, int n) {
		if (anyOldOrderValues == null){
			throw new RuntimeException("The anyOldOrderValues cann't be null.");
		}
		if (anyOldOrderValues.length < n){
			throw new RuntimeException("The parameter n must <= anyOldOrderValues.length");
		}
		Arrays.sort(anyOldOrderValues);
		int lastIndex = anyOldOrderValues.length - 1;
		int[] values = new int[n];
		for (int i=0; i<n; ++i){
			values[i] = anyOldOrderValues[lastIndex - i];
		}
		return values;
	}
}
